paquetes

library (DT)
library (dplyr)
library (terra)
library (raster)
library (leaflet)
library (sf)
library (ggplot2)
library (plotly)

capas

provincias <-
  st_read(
    "https://github.com/tpb728O-programaciongeoespacialr/2021ii/raw/main/datos/ign/delimitacion-territorial-administrativa/provincias.geojson",
    quiet = TRUE
  )
provincias <-
  provincias %>%
  st_transform(4326)
cuencas <-
  st_read(
    "https://raw.githubusercontent.com/MaureenArg/datostarea/master/cuencas.geojson",
    quiet = TRUE
  )
altitud <-
  rast(
    "/vsicurl/https://raw.githubusercontent.com/tpb728O-programaciongeoespacialr/2021ii/master/datos/worldclim/altitud.tif"
  )
denu_depu <-
  st_read(
    "/vsicurl/https://raw.githubusercontent.com/MaureenArg/datostarea/master/denu_depu.csv",
    options = c(
      "X_POSSIBLE_NAMES=decimalLongitude",
      "Y_POSSIBLE_NAMES=decimalLatitude"
    ),
    quiet = TRUE
  )
st_crs (denu_depu) <- 4326

tabla

denu_depu %>%
  st_drop_geometry()%>%
  select (TIPO_den, año, TIPO_inf, CATEGORIA_) %>%
    datatable (rownames= FALSE, filter= "top", class= "hover cell-border stripe", caption= "Tabla 1: Tipo de denuncias ambientales según año", colnames = c( "Tipo de denuncia", "Año", "Detalle de la denuncia", "Categoría"), extensions = "Buttons", options = list (language = list (url = "//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json"),dom = "Bfrtip", buttons = c("csv", "excel", "pdf")))

mapa

altitud_rl <- raster(altitud)
leaflet() %>%
  addTiles (group = "OSM") %>%
  addProviderTiles("Esri", group = "Esri") %>%
  addProviderTiles("CartoDB", group = "CartoDB") %>%
  addRasterImage(
    altitud_rl, 
    opacity = 0.6
  ) %>% 
   addPolygons(
    data = cuencas,group = "Cuencas hidrográficas", 
    color = "black",
    fillColor = "blue",
    stroke = TRUE,
    weight = 1.0, popup = ~NOMBRE,
  ) %>%
  
  addPolygons(
    data = provincias,group = "Provincias", 
    color = "black",
    fillColor = "Transparent",
    stroke = TRUE, popup = ~provincia, 
    weight = 1.0
  ) %>%
  
  addCircleMarkers(
    data = denu_depu,
    stroke = F,
    radius = 4,
    fillColor = 'red',
    fillOpacity = 0.5, popup = ~TIPO_inf,
  ) %>%
addLayersControl(baseGroups = c ("OSM", "Esri", "CartoDB", "Cuencas hidrográficas", "Provincias"))
## Warning in validateCoords(lng, lat, funcName): Data contains 1 rows with either
## missing or invalid lat/lon values and will be ignored
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded ellps WGS 84 in Proj4 definition: +proj=merc +a=6378137
## +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null
## +wktext +no_defs +type=crs
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded datum World Geodetic System 1984 in Proj4 definition
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded ellps WGS 84 in Proj4 definition: +proj=merc +a=6378137
## +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null
## +wktext +no_defs +type=crs
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded datum World Geodetic System 1984 in Proj4 definition

addProviderTiles(providers\(Esri.WorldImagery, group = "Esri") %>% addLayersControl(baseGroups = c("OSM")) addProviderTiles(providers\)Esri.WorldImagery)

#Graficos

denuncias2021 <-
read.csv (
  file= "https://raw.githubusercontent.com/MaureenArg/datostarea/master/denunciasoct23.csv", 
 sep = ";"
    )

Generación de un nuevo data frame

denuncias_anio <-
  denuncias2021 %>%
   dplyr::count(anio)

Grafico barras

barplot(
  denuncias_anio$n, 
  names.arg = denuncias_anio$anio,
  xlab= "Año",
  ylab= "Cantidad de denuncias",
  main = "Cantidad de denuncias ambientales en Costa Rica (2018-2019)",
)

denuncias_x_anio <-
  denuncias2021 %>%
  select (anio, Forestal, Suelo, Agua, Aire, Vida.silvestre, Mineria) %>%
  group_by ( anio) %>%
  summarise (Forestal = sum (Forestal), Suelo = sum (Suelo), Agua = sum (Agua), VidaSilvestre = sum (Vida.silvestre), Mineria = sum (Mineria))

denuncias_x_anio
## # A tibble: 2 x 6
##    anio Forestal Suelo  Agua VidaSilvestre Mineria
##   <int>    <int> <int> <int>         <int>   <int>
## 1  2018       25    89    48            41      49
## 2  2019       47    88    37            56      30
denuncias_x_tipo <-
  denuncias2021 %>%
  select (afectado, denuncias) %>%
  group_by (afectado) %>%
  summarise (denuncias = sum (denuncias))

denuncias_x_tipo
## # A tibble: 6 x 2
##   afectado       denuncias
##   <chr>              <int>
## 1 Agua                  85
## 2 Aire                  24
## 3 Forestal              72
## 4 Mineria               79
## 5 Suelo                177
## 6 Vida silvestre        97

grafico ggplot

ggplot () + geom_col (
  data = denuncias_x_tipo, 
  aes (x = afectado, fill =  afectado, 
      y = denuncias, fill = "denuncias"), width = 0.9) +
  ggtitle ("Cantidad de denuncias según tipo para el periodo 2018-2019") +
  xlab ("Tipo de denuncias") +
  ylab ("Cantidad de denuncias") +
  scale_fill_manual (values = c ("#0000FF", "#CDC0B0", "#458B00","#EEAD0E" ,"#8B7355", "#BF3EFF")) +
  theme (
    legend.title = element_blank(), legend.position = "left", plot.title = element_text (size = 13))
## Warning: Duplicated aesthetics after name standardisation: fill

denuncias_anio %>% filter (anio == 2018) %>% ## grafico plotly

  plot_ly( x=  c(2018,2019), y=  c(256,278), type= "bar", mode= "markers",
   fill="tozeroy", color= I("blue")) %>%
  layout (title= "Cantidad de denuncias ambientales por año", xaxis= list (title= "Año"), yaxis= list (title= "Cantidad de denuncias"))
## Warning: 'bar' objects don't have these attributes: 'mode', 'fill'
## Valid attributes include:
## 'type', 'visible', 'showlegend', 'legendgroup', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'selectedpoints', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'xperiod', 'yperiod', 'xperiod0', 'yperiod0', 'xperiodalignment', 'yperiodalignment', 'text', 'texttemplate', 'hovertext', 'hovertemplate', 'textposition', 'insidetextanchor', 'textangle', 'textfont', 'insidetextfont', 'outsidetextfont', 'constraintext', 'cliponaxis', 'orientation', 'base', 'offset', 'width', 'marker', 'offsetgroup', 'alignmentgroup', 'selected', 'unselected', 'r', 't', '_deprecated', 'error_x', 'error_y', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'xsrc', 'ysrc', 'textsrc', 'texttemplatesrc', 'hovertextsrc', 'hovertemplatesrc', 'textpositionsrc', 'basesrc', 'offsetsrc', 'widthsrc', 'rsrc', 'tsrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'
Tipos <- c ("Agua", "Aire", "Forestal", "Mineria", "Suelo", "Vida Silvestre" )
año2018 <- c (48,4,25,49,89,41)
año2019 <- c (37,20,47,30,88,56)
data <- data.frame (Tipos, año2018, año2019)
plot_ly (data, x= ~Tipos, y= ~año2018, type = "bar", name = "2018")%>%
add_trace(y= ~año2019, name= "2019")%>%
layout (yaxis= list(title="Cantidad"), barmode="group")%>%
layout (title= "Cantidad de denuncias ambientales por año", xaxis= list (title= "Tipo de denuncia"), yaxis= list (title= "Cantidad de denuncias"))